import logo from '@/assets/b_logo1.png';
import { customer } from '@/components/TopInfo/data';
import { getOrderDetail, handleDownloadImg } from '@/services/center';
import { donwLoadFile, jumpUrl, useUrlParams } from '@/utils';
import { statusList } from '@/utils/common';
import { useRequest } from 'ahooks';
import { Affix, Button, Card, Divider, Flex, Space, Tabs, Typography } from 'antd';
import dayjs from 'dayjs';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import { useRef, useState } from 'react';
import { FormattedMessage, useIntl, useLocation } from 'umi';
import ApplyTable from './components/ApplyTable';
import UserData from './components/Data';
import './index.less';
const OrderDetail: React.FC = () => {
  const location = useLocation();
  const search = decodeURIComponent(location.search);
  const id = useUrlParams('id', search);
  const index = useUrlParams('index', search);
  const merchantLogo = useUrlParams('logo', search);
  const typeName = useUrlParams('typeName', search);
  const statusName = useUrlParams('statusName', search);
  const { data: val, loading } = useRequest(() => {
    return getOrderDetail(id);
  });
  const data = val?.data || {};
  const [btnLoading, setBtnLoading] = useState(false);

  const { productName, orderUserStatus: status, createdDate, orderNo } = data?.detail || {};
  const intl = useIntl();

  const { color, bgColor } = statusList(status?.toString()) || {};
  const { proofList = [] } = (data as any) || {};
  const childRef: any = useRef(null);
  //  这里用于存储图像(以免跳到第二步取不了dom)
  const [img, setImg] = useState<any>('');

  const dataURLtoFile = (dataURL: any, filename: any) => {
    const arr = dataURL.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
  };
  const drawImg = async () => {
    if (index) {
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      setActiveTab(list[Number(index)].key);
    }
    /** html2canvas：将html转化成canvas图片 */
    if (childRef.current) {
      const canvas = await html2canvas(childRef.current, {
        useCORS: true, // 【重要】开启跨域配置
        allowTaint: true, // 允许跨域图片
        // foreignObjectRendering: true, // 是否在浏览器支持的情况下使用ForeignObject渲染
        // async: false, // 是否异步解析和呈现元素
        /** 以下字段必填 */
        scale: 2, // 处理模糊问题
        backgroundColor: '#fff',
      });
      const contentWidth = canvas.width;
      const contentHeight = canvas.height;

      //一页pdf显示html页面生成的canvas高度;
      const pageHeight = (contentWidth / 592.28) * 841.89;
      //未生成pdf的html页面高度
      let leftHeight = contentHeight;
      //pdf页面偏移
      let position = 0;
      //html页面生成的canvas在pdf中图片的宽高（a4纸的尺寸[595.28,841.89]）
      const imgWidth = 595.28;
      const imgHeight = (592.28 / contentWidth) * contentHeight;

      const pageData = canvas.toDataURL('image/jpeg', 1.0);
      const pdf = new jsPDF('p', 'pt', 'a4');

      //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
      //当内容未超过pdf一页显示的范围，无需分页
      if (leftHeight < pageHeight) {
        pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
      } else {
        while (leftHeight > 0) {
          pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
          leftHeight -= pageHeight;
          position -= 841.89;
          //避免添加空白页
          if (leftHeight > 0) {
            pdf.addPage();
          }
        }
      }

      setImg(pdf);
    }
  };
  const list = [
    {
      key: 'apply',
      label: <FormattedMessage id="home.apply_loan_table" />,
      children: (
        <ApplyTable
          onOk={drawImg}
          loading={loading}
          ref={childRef as any}
          data={data?.detail || {}}
        />
      ),
      forceRender: true,
    },
    {
      key: 'data',
      label: <FormattedMessage id="home.apply_loan_img" />,
      children: <UserData data={proofList} />,
      forceRender: true,
    },
  ];
  const [activeTab, setActiveTab] = useState(list[0].key);

  // 使用html2canvas将html转化成canvast图片后转换成pdf

  const downLoadImg = async () => {
    const name = 'info.pdf';
    const formData = new FormData();
    const base64 = img.output('datauristring');

    const file = dataURLtoFile(base64, name);
    formData.append('file', file);
    setBtnLoading(true);
    try {
      const data: any = await handleDownloadImg(formData, id);

      if (data) {
        donwLoadFile(data);
      }
      setBtnLoading(false);
    } catch {
      setBtnLoading(false);
    }
  };
  return (
    <div className="orderDetail">
      <Affix>
        <div
          style={{
            background: '#fff',
            padding: '17px 0',
            boxShadow: '0px 4px 13.9px 0px #00000012',
          }}
        >
          <div className="a_common">
            <Flex justify="space-between" align="center">
              <img
                style={{ cursor: 'pointer' }}
                onClick={() => {
                  jumpUrl('/');
                }}
                src={logo}
                width={130}
                height={35}
              />
              <Button
                loading={loading || btnLoading}
                style={{ borderRadius: 8, minWidth: 120 }}
                size="large"
                type="primary"
                onClick={() => {
                  downLoadImg();
                }}
              >
                {intl.formatMessage({ id: 'order.donwload' })}
              </Button>
            </Flex>
          </div>
        </div>
      </Affix>
      <div style={{ background: '#F2F8FC', minHeight: '100vh' }}>
        {Object.keys(data).length > 0 && data ? (
          <div className="orderDetail_content a_common">
            <div className="orderDetail_top">
              <div style={{ color: '#fff', marginBottom: 4 }}>{typeName}</div>
              <Flex align="center" gap={8}>
                <div
                  style={{
                    padding: '0 3px',
                    height: '26px',
                    background: '#FFFFFF',
                    borderRadius: 4,
                  }}
                >
                  <img src={merchantLogo} height={23} />
                </div>

                <Typography.Text
                  ellipsis={{ tooltip: productName }}
                  style={{
                    fontSize: 26,
                    color: '#fff',
                    fontWeight: 'bold',
                    whiteSpace: 'nowrap',
                  }}
                >
                  {productName}
                </Typography.Text>

                <div
                  style={{
                    padding: '9px 25px ',
                    color,
                    backgroundColor: bgColor,
                    borderRadius: 8,
                    whiteSpace: 'nowrap',
                  }}
                >
                  {statusName}
                </div>
              </Flex>

              <Flex align="center" style={{ color: '#fff', marginTop: 9 }}>
                <div>
                  {intl.formatMessage({ id: 'center.apply_id' })}：{orderNo}
                </div>
                <Divider className="apply_modal_top_line" type="vertical" />
                <div>
                  {intl.formatMessage({ id: 'center.apply_time' })}：
                  {dayjs(createdDate).format('YYYY-MM-DD HH:mm:ss')}
                </div>
              </Flex>
              <Space style={{ color: '#fff', marginTop: 4 }} size={0}>
                <div style={{ marginRight: 3 }}>
                  {intl.formatMessage({ id: 'home.apply_follow_manager' })}
                </div>
                {customer}
              </Space>
            </div>
            <div className="orderDetail_main">
              <Tabs
                activeKey={activeTab}
                onChange={(key) => {
                  setActiveTab(key);
                }}
                destroyInactiveTabPane={false}
                items={list}
                tabBarGutter={145}
                centered
              />
            </div>
          </div>
        ) : (
          <div className="a_common" style={{ paddingTop: '30px' }}>
            <Card bordered={false} style={{ boxShadow: 'none' }} loading={loading} />
          </div>
        )}
      </div>
    </div>
  );
};
export default OrderDetail;
